﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Outdoors.Resources;
using System.Device.Location;
using Windows.Devices.Geolocation;
using System.Net.Http;
using Outdoors.Helpers.Flickr;
using Outdoors.Helpers.Icons;
using Outdoors.Helpers.Foursquare;
using Outdoors.ViewModels;

namespace Outdoors
{
    public partial class MainPage : PhoneApplicationPage
    {
        private double Latitude { get; set; }
        private double Longitude { get; set; }
        private string CategoryId { get; set; }

        public MainPage()
        {
            InitializeComponent();

            Loaded += MainPage_Loaded;
        }

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            UpdateTiles();
        }
        private async void UpdateTiles()
        {
            var foursquareVenues = new List<FoursquareVenue>();
            try
            {
                foursquareVenues = await FoursquareVenue.GetFoursquareVenues(Latitude, Longitude, CategoryId);
            }
            catch (Exception e)
            { }

            var placeViewModel = new PlaceViewModel();
            placeViewModel.LoadData(foursquareVenues);

            DataContext = placeViewModel;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            Latitude = Convert.ToDouble(NavigationContext.QueryString["latitude"]);
            Longitude = Convert.ToDouble(NavigationContext.QueryString["longitude"]);
            CategoryId = NavigationContext.QueryString["categoryId"];
        }

        private void Places_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selector = sender as LongListSelector;

            if (selector == null)
                return;

            var selectedItem = selector.SelectedItem as PlaceItemViewModel;

            string navigateTo = string.Format("/DetailsPage.xaml?&latitude={0}&longitude={1}&name={2}", selectedItem.Latitude, selectedItem.Longitude, selectedItem.Name);
            NavigationService.Navigate(new Uri(navigateTo, UriKind.RelativeOrAbsolute));
        }
    }
}